//
//  AccountViewModel.swift
//  HyWeibo
//
//  Created by HY-Mac on 16/7/7.
//  Copyright © 2016年 HY-Mac. All rights reserved.
//

import UIKit
import AFNetworking

class AccountViewModel: NSObject {
    
    var account: UserAccount?
    
    var userLogin: Bool{
    
        return account?.access_token != nil
    }
    
    
    override init() {
        super.init()
        account = UserAccount.loadUserAccount()
        
    }
    
    
    func loadTokenInfo(code: String, finished: (error: NSError?) -> ()){
        let urlString  = "https://api.weibo.com/oauth2/access_token"
        let parameter = ["client_id": appid, "client_secret": appSercet, "grant_type": "authorization_code", "code": code, "redirect_uri": redirect_uri]
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        AFN.POST(urlString, parameters: parameter, success: { (_, result) in
            //print(result)
            if let dict = result as? [String: AnyObject]{
                //let access_token = dict["access_token"] as? String
                //let uid = dict["uid"] as? String
                let userAccount = UserAccount(dict: dict)
                //print(userAccount)
                self.loadUserInfo(userAccount, finished: finished)
            }
            
        }) { (_, error) in
            //print(error)
        
            
        }
        
    }
    
    func loadUserInfo(userAccount: UserAccount, finished: (error: NSError?) -> ()){
        let urlString = "https://api.weibo.com/2/users/show.json"
        let AFN = AFHTTPSessionManager()
        let parameter = ["access_token": userAccount.access_token!, "uid": userAccount.uid!]
        AFN.GET(urlString, parameters: parameter, success: { (_, result) in
            //print(result)
            if let dict = result as? [String: AnyObject]{
                userAccount.avatar_large = dict["avatar_large"] as? String
                userAccount.name = dict["name"] as? String
                // userAccount.expires_in = dict["expires_in"] as? NSTimeInterval
                // print(userAccount)
                userAccount.saveUserAccount()
                NSNotificationCenter.defaultCenter().postNotificationName(HYChangeRootViewController, object: false)
                NSNotificationCenter.defaultCenter().postNotificationName("AccountViewModelLoadUserInfo", object: nil)
                finished(error: nil)
            }
        }) { (_, error) in
           // print(error)
            finished(error: error)
        }}
}

